package kr.hkit.androidcomplete03.ch22;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;


public class SurView extends SurfaceView implements Callback {

	ArrayList<Ball> arBall;
	final static int DELAY = 50;
	SurfaceHolder mHolder;
	DrawThread mThread;
	
	public SurView(Context context) {
		super(context);
		mHolder = getHolder();
		getHolder().addCallback(this);	//	표면에 변화가 생길 때마다 불러줌
		arBall = new ArrayList<>();
	}

	// 그리기가 가능
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		mThread = new DrawThread(mHolder);
		mThread.start();
	}

	// 그릴 영역을 알려줌.
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		if(mThread != null){
			mThread.sizeChanged(width, height);
		}

	}

	// 터치한 곳에서부터 공이 생성
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			synchronized(mHolder){
				Ball newBall = Ball.Create((int)event.getX(), (int)event.getY());
				arBall.add(newBall);
				return true;
			}
		}
		return false;
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mThread.bExit = true;
		for(;;){
			try{
				mThread.join();
				break;
			} catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	class DrawThread extends Thread{
		boolean bExit;
		int mWidth, mHeight;
		SurfaceHolder mHolder;
		
		public DrawThread(SurfaceHolder mHolder) {
			this.mHolder = mHolder;
		}
		
		public void sizeChanged(int width, int height){
			mWidth = width;
			mHeight = height;
		}

		// 시작 시 수행
		@Override
		public void run() {
			Canvas canvas;
			Ball B;
			
			while(!bExit){
				for(int i=0; i<arBall.size(); i++){
					B = arBall.get(i);
					B.Move(mWidth, mHeight);
					if(B.count > 4){
						arBall.remove(i);
						i--;
					}
				} // end of for
				
				synchronized (mHolder) {
					canvas = mHolder.lockCanvas();
					
					if(canvas == null)
						canvas.drawColor(Color.WHITE);
					
					for(int i=0; i<arBall.size(); i++){
						arBall.get(i).Draw(canvas);
						if(bExit)
							break;
					}
					
					//canvas.drawColor(Color.BLACK);
					mHolder.unlockCanvasAndPost(canvas);
				}
				
				try{
					sleep(SurView.DELAY);
				} catch(InterruptedException e){
					
				}
			} // end of while
		}
	}

}
